<?php
/**
 * author by OCY, 2021/07/01 20:06.
 */

class Express
{
	private $key;
	private $customer;
	private $secret;
	private $userid;

	public function __construct()
	{
		$this->key = 'sJjpSwgs2392';
		$this->customer = 'C1934B28ED1FEF6C9F4E340FD4B3928D';
		$this->secret = 'acec18f172834d17ac8bc49d23789695';
		$this->userid = 'b485167b05d44dc09a3b33ee8d4978c8';
	}

	/**
	 * 实时查询
	 * @param        string        $com             快递公司编码
	 * @param        string        $num             快递单号
	 * @param        string        $phone           手机号
	 * @param        string        $from            出发地城市
	 * @param        string        $to              目的地城市
	 * @param        string        $resultv2        开启行政区域解析
	 * @return       json
	 * */
	public function synquery($com, $num, $phone = '', $from = '', $to = '', $resultv2 = '0')
	{
		if (empty($com)) apiReturn(2, '快递公司编码缺失');
		if (empty($num)) apiReturn(2, '快递单号缺失');

		$url = 'http://poll.kuaidi100.com/poll/query.do';

		$param = array(
			'com' => $com,
			'num' => $num,
			'phone' => $phone,
			'from' => $from,
			'to' => $to,
			'resultv2' => $resultv2
		);

		$post_data = array();
		$post_data["customer"] = $this->customer;
		$post_data["param"] = json_encode($param);
		$sign = md5($post_data["param"] . $this->key . $post_data["customer"]);
		$post_data["sign"] = strtoupper($sign);

		$params = "";
		foreach ($post_data as $k => $v) {
			$params .= "$k=" . urlencode($v) . "&";              //默认UTF-8编码格式
		}
		$post_data = substr($params, 0, -1);

		$data = $this->sendCurl($url, $post_data);

		return $data;
	}

	/**
	 * 发送post请求
	 * */
	public function sendCurl($url, $post_data)
	{
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		$result = curl_exec($ch);
		$data = json_decode($result);

		return $data;
	}

}